package _37_数字在排序数组中出现的次数;

/**
 * 用二分法找到该数字
 */
public class Solution {
    public int GetNumberOfK(int[] array, int k) {
        if (array.length == 0) return 0;
        int start = 0, end = array.length - 1;
        int mid = 0;
        int count = 0;
        while (start <= end) {
            mid = start + (end - start) / 2;
            if (array[mid] == k) {
                count++;
                break;
            } else if (array[mid] > k) {
                end = mid - 1;
            } else start = mid + 1;
        }
        System.out.println(start);
        int a = mid - 1, b = mid + 1;
        while (a >= 0 && array[a] == k) {
            a--;
            count++;
        }
        while (b < array.length && array[b] == k) {
            b++;
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        int nums[] = {1, 1, 1, 1, 3, 3, 3, 3, 4, 5, 5, 7, 9, 11, 13, 13, 13, 13, 13, 13};
        Solution solution = new Solution();
        System.out.println(solution.GetNumberOfK2(nums, 13));
    }

    //方法2
    public int GetNumberOfK2(int[] array, int k) {
        int length = array.length;
        if (length == 0) {
            return 0;
        }
        int firstK = searchFirst(array, k);
        int lastK = searchLast(array, k);


        if (firstK != -1 && lastK != -1) {
            return lastK - firstK + 1;
        }
        return 0;
    }

    public int searchFirst(int[] array, int k) {
        if (array.length == 0) return -1;
        int start = 0, end = array.length - 1;
        int mid = 0;
        while (start <= end) {
            mid = start + (end - start) / 2;
            if (array[mid] > k) {
                end = mid - 1;
            } else if (array[mid] < k) {
                start = mid + 1;
            } else if (mid - 1 >= 0 && array[mid - 1] == k) {
                end = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    public int searchLast(int[] array, int k) {
        if (array.length == 0) return -1;
        int start = 0, end = array.length - 1;
        int mid = 0;
        while (start <= end) {
            mid = start + (end - start) / 2;
            if (array[mid] > k) {
                end = mid - 1;
            } else if (array[mid] < k) {
                start = mid + 1;
            } else if (mid + 1 < array.length && array[mid + 1] == k) {
                start = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
